package com.huimingpay.merchant.common.intercept;

import com.huimingpay.common.domain.BusinessException;
import com.huimingpay.common.domain.CommonErrorCode;
import com.huimingpay.common.domain.ErrorCode;
import com.huimingpay.common.domain.RestErrorResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理器
 */
@ControllerAdvice  //Controller的增强注解
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //捕获所有异常
    @ExceptionHandler(Exception.class) //配合ControllerAdvice注解实现全局异常处理
    @ResponseBody //返回json格式
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //INTERNAL_SERVER_ERROR 500 服务器内部错误
    public RestErrorResponse processException(HttpServletRequest request,
                                              HttpServletResponse response,
                                              Exception e) {
        //解析异常信息，判断异常的类型
        //如果是系统自定义异常，直接取出errCode和errMessage
        if (e instanceof BusinessException) {
            LOGGER.info(e.getMessage(), e); //记录日志
            //解析系统自定义异常信息
            BusinessException businessException = (BusinessException) e;
            ErrorCode errorCode = businessException.getErrorCode();
            // 获取错误信息
            int code = errorCode.getCode();
            String desc = errorCode.getDesc();
            return new RestErrorResponse(String.valueOf(code), desc); //返回错误信息
        }
        //如果是其他异常，直接返回未知错误99999
        LOGGER.error("系统异常", e);
        //统一定义为99999系统未知错误
        return new RestErrorResponse(String.valueOf(CommonErrorCode.UNKNOWN.getCode()), CommonErrorCode.UNKNOWN.getDesc());
    }

}